package middle

import (
	"gim-server/comsvc"
	"gim-server/consts"
	"gim-server/errs"
	"gim-server/utils"
	"github.com/gin-gonic/gin"
)

func OpenAuth() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		appId := ctx.Request.Header.Get(consts.AppID)
		tokenStr := ctx.Request.Header.Get(consts.Token)
		info, err := comsvc.GetAppInfo(appId)
		if err != nil {
			utils.ERR(ctx, &utils.ErrArgs{
				Code: errs.ApiRecordNotFound,
				Err:  err,
				Msg:  "无效APP_CONFIG",
			})
			ctx.Abort()
			return
		}
		if tokenStr != info.Token {
			utils.ERR(ctx, &utils.ErrArgs{
				Code: errs.ApiTokenErr,
				Err:  err,
				Msg:  "无效TOKEN",
			})
			ctx.Abort()
			return
		}
		ctx.Set(consts.AppID, appId)
		ctx.Set(consts.AppInfo, info)
		ctx.Next()
	}
}
